<script setup lang="ts">
import type { CheckboxGroup } from "./api/type"

// 引入通用多选组件
import { ElMessage, ElNotification } from "element-plus"
import { onMounted, ref } from "vue"
import MultiCheckboxGroup from "@/layouts/components/MultiCheckboxGroup/index.vue"

// 引入API
import { fetchSystemParams, submitSystemParams } from "./api/index"

// 状态管理
const loading = ref(true)
const submitting = ref(false)
const paramGroups = ref<CheckboxGroup[]>([])
// 保存原始数据用于对比
const originalParamGroups = ref<CheckboxGroup[]>([])

// 初始化：请求后端参数配置
onMounted(async () => {
  try {
    const res = await fetchSystemParams()
    if (res.code === 200) {
      // 深拷贝避免引用问题
      paramGroups.value = JSON.parse(JSON.stringify(res.data.paramGroups))
      originalParamGroups.value = JSON.parse(JSON.stringify(res.data.paramGroups))
    } else {
      ElMessage.error(res.message || "加载参数失败")
    }
  } catch (err: any) {
    console.error("加载失败:", err)
    ElMessage.error("系统异常，请重试")
  } finally {
    loading.value = false
  }
})

// 检查是否有修改
function hasChanges() {
  return JSON.stringify(paramGroups.value) !== JSON.stringify(originalParamGroups.value)
}

// 提交参数到后端
async function handleSubmit() {
  // 检查是否有修改
  if (!hasChanges()) {
    ElMessage.info("未检测到参数变化，无需提交")
    return
  }

  submitting.value = true
  try {
    const res = await submitSystemParams(paramGroups.value)
    if (res.code === 200) {
      ElMessage.success("参数提交成功")
      // 提交成功后更新原始数据
      originalParamGroups.value = JSON.parse(JSON.stringify(paramGroups.value))
      ElNotification({
        title: "提示",
        message: "参数已生效，部分设置可能需要刷新页面",
        type: "success",
        duration: 3000
      })
    } else {
      ElMessage.error(res.message || "提交失败，请重试")
    }
  } catch (err: any) {
    console.error("提交失败:", err)
    ElMessage.error("系统异常，提交失败")
  } finally {
    submitting.value = false
  }
}

// 重置参数
function handleReset() {
  if (!hasChanges()) {
    ElMessage.info("当前参数未修改，无需重置")
    return
  }

  // 重置为原始数据
  paramGroups.value = JSON.parse(JSON.stringify(originalParamGroups.value))
  ElMessage.success("已重置为原始参数")
}
</script>

<template>
  <div class="system-params-page">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2>系统参数配置</h2>
      <p class="sub-title">
        配置系统各模块功能参数，修改后即时生效
      </p>
    </div>

    <!-- 加载态 -->
    <el-skeleton
      v-if="loading"
      :loading="loading"
      :rows="5"
      style="padding: 24px;"
      :animated="true"
    />

    <!-- 参数分组渲染 -->
    <div v-else class="params-container">
      <!-- 无数据提示 -->
      <div v-if="paramGroups.length === 0" class="empty-state">
        <el-empty description="暂无参数配置数据" />
      </div>

      <template v-else>
        <div
          v-for="(group, idx) in paramGroups"
          :key="idx"
          class="param-group-card"
        >
          <MultiCheckboxGroup
            :group-title="group.groupTitle"
            :tip="group.tip"
            :options="group.options"
            v-model="group.checkedValues"
            :disabled="loading || submitting"
          />
        </div>
      </template>

      <!-- 操作按钮组 -->
      <div class="btn-group" v-if="paramGroups.length > 0">
        <el-button
          type="primary"
          @click="handleSubmit"
          :loading="submitting"
        >
          提交参数
        </el-button>
        <el-button
          @click="handleReset"
        >
          重置
        </el-button>
      </div>
    </div>
  </div>
</template>

<style scoped lang="scss">
.system-params-page {
  padding: 24px;
  background: #fff;
  min-height: calc(100vh - 64px);

  .page-header {
    margin-bottom: 24px;
    padding-bottom: 16px;
    border-bottom: 1px solid #f0f0f0;

    h2 {
      font-size: 18px;
      font-weight: 600;
      margin-bottom: 8px;
      color: #333;
    }

    .sub-title {
      color: #666;
      font-size: 14px;
    }
  }

  .params-container {
    border: 1px solid #eee;
    padding: 24px;
    border-radius: 4px;
    transition: all 0.3s;

    &:hover {
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
    }
  }

  .param-group-card {
    margin-bottom: 24px;
    padding-bottom: 16px;
    border-bottom: 1px dashed #eee;

    &:last-child {
      border-bottom: none;
      margin-bottom: 0;
      padding-bottom: 0;
    }
  }

  .empty-state {
    text-align: center;
    padding: 48px 0;
  }

  .btn-group {
    margin-top: 32px;
    text-align: center;

    .el-button {
      margin-left: 8px;
    }
  }
}
</style>
